<script src="/bootstrap/js/bootstrap.min.js"></script>
<script src="/js/jquery.cookie.js"></script>
<div id="page">
	<%= form_for(@doc) do |f| %>
	<div class="mod-note-button">
		<div id="alertIng" class="alert alert-info hide">
              <button type="button" class="close" data-dismiss="alert">×</button>
              <strong>亲爱的：</strong> 我正在努力保存中～
        </div>
		<div id="alertOk" class="alert alert-success hide">
              <button type="button" class="close" data-dismiss="alert">×</button>
              <strong>太棒了！</strong> 该文档已经成功保存！
        </div>
        <div id="alertError" class="alert alert-error hide">
              <button type="button" class="close" data-dismiss="alert">×</button>
              <strong>糟糕！</strong> 保存失败 -_-! 貌似你的网络出现了一些状况？
            </div>
		<input type="button" class="btn btn-mini" value="≡ 返回列表" onclick="__list();" />
		<input type="button" id="btnSave" value="⊙ 保存文档" class="btn btn-mini btn-primary" onclick="save_before();" />
		<input type="button" class="btn btn-mini" value="◇ 刷新页面" onclick="__reload();" />
		<input type="button" id="btnShow" class="btn btn-mini hide" value="☆ 查看文档" onclick="show();" />
		<% if(@lastdocs != nil && @lastdocs.length > 0) %>
			<div class="btn-group">
                <button id="btnLaster" class="btn btn-mini dropdown-toggle" data-toggle="dropdown">≈ 最近编辑 <span class="caret"></span></button>
                <ul class="dropdown-menu">
                	<% @lastdocs.each do|doc| %>
                  	<li><a href="/doc/edit/<%=doc.id%>"><%=doc.title%></a></li>
                  	<% end %>
                </ul>
              </div>
        <% end %>

	</div>
	<div class="mod-note-title">
		<div>标题：<%= f.text_field :title, :style=>"width: 440px" %>&nbsp;&nbsp;
			类别：<%= select(:doc_main, :cateid, @user.doccategorys.collect {|p| [ p.name, p.id ] }, { :include_blank => false }, :style=>'width:150px;') %><input type="hidden" id="__cateid" value="<%=@doc.cateid%>" />&nbsp;&nbsp;
			<label style="display:inline;"><%= f.check_box :shareid %>&nbsp;其他人可见</label>
		</div>
		<div class="desc"></div>
	</div>
	<div class="content">
		<%= f.text_area :content, :cols => '86', :rows=>'20'%>
		<%= f.hidden_field :wordcount %>
		<%= f.hidden_field :id %>
		<div style="font-size:11px; padding-top:3px; color:rgb(153,153,159)"><span style="background-color: rgb(252,101,84); padding:1px; color:#fff; ">小提示：</span> 如果您要换行，请使用 Shift + 回车；如果您想新起一段落，直接回车即可。</div>
	</div>
	<% end %>
</div>

<script type="text/javascript" src="/js/tinymce/tinymce.min.js"></script>
<script type="text/javascript">
	$().ready(function(){
		tinymce.init({
		    selector: "textarea",
		    language: "zh_CN",
		    plugins: [
		        "advlist autolink lists link image charmap print preview hr anchor pagebreak",
		        "searchreplace visualblocks visualchars code fullscreen",
		        "insertdatetime media nonbreaking save table contextmenu directionality",
		        "emoticons paste textcolor"
		    ],
		    toolbar1: "insertfile undo redo | styleselect | bold italic | forecolor backcolor fontsizeselect | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
		    //toolbar2: "print preview media | forecolor backcolor emoticons",
		    image_advtab: true,
		    setup: function(editor) {
		    	editor.on('change', function(e) {
		    		$('#btnSave').removeAttr('disabled');
		        });
		        editor.on('keyup', function(e) {
		        	$('#btnSave').removeAttr('disabled');
		        });
		   	}
		});

		$.ajaxSetup({  
		    beforeSend: function(xhr) {  
		        xhr.setRequestHeader("X-CSRF-Token", $("meta[name=\"csrf-token\"]").attr("content"));  
		    }  
		});

		// 显示文档按扭
		showButton();

		// 冻结保存按扭
		setSaveButtonState(false);

		// 恢复按扭
		$('#doc_main_title').keyup(function(){ setSaveButtonState(true); });
		$('#doc_main_cateid').change(function(){ setSaveButtonState(true); });
		$('#doc_main_shareid').click(function(){ setSaveButtonState(true); });

	});

	// 刷新页面
	function __reload(){
		var id = $('#doc_main_id').val();
		if(id != '' && id != '0') {
			location.href = '/doc/edit/' + id;
		} else {
			location.href = location.href;
		}
	}

	// 返回列表
	function __list() {
		if($('#btnSave:disabled').length == 0) {
			if(!confirm('亲爱的，您的文档的最后一次修改可能未保存。\n是否离开该页面？')) {
				return;
			}
		}
		location.href='/doc/';
	}

	// 是否冻结保存按扭
	function setSaveButtonState(isRunning){
		if(isRunning) {
			$('#btnSave').removeAttr('disabled');
		} else {
			$('#btnSave').attr('disabled', 'true');
		}
	}

	// 显示文档按钮
	function showButton() {
		var id = $('#doc_main_id').val();
		if(id != '' && id != '0') {
			$('#btnShow').removeClass('hide');
		} else {
			$('#btnShow').addClass('hide');
		}
	}

	// 获取最终页地址
	var __detailUrl = '<%=@detail_url%>';
	function getDetailUrl(docid){
		if(__detailUrl == '') {
			$.getJSON('/doc/getdetailurl/' + docid, function(data) {
				__detailUrl = data.url;
			})
		}
	}

	// 显示文档内容
	function show() {
		var id = $('#doc_main_id').val();
		if(id != '' && id != '0') {
			var url = '/doc/show/' + id;
			if(__detailUrl != '') url = __detailUrl;
			window.open(url);
		}
	}



	// 保存文档
	function __save(docid, title, cateid, content, wordcount, shareid) {
		$('#btnSave').attr('disabled', 'true');
		$('#alertIng').slideDown(); // 保存中
		$.ajax({
			type: 'POST',
			url: '/doc/save',
			data: {
			'id':docid,
			'title':title,
			'cateid':cateid,
			'content':content,
			'wordcount':wordcount,
			'shareid': shareid
			},
			success: function(data){
				if(data > 0){
					showTip(true);
					$('#doc_main_id').val(data);
					addCookie(data);
					getDetailUrl(data);
					showButton();
				} else {
					showTip(false);
					$('#btnSave').removeAttr('disabled');
				}
			},
			error: function(){
				showTip(false);
				$('#btnSave').removeAttr('disabled');
			}
		});
	}

	// 保存提示语
	function showTip(result) {
		$('#alertIng').hide();
		$('#alertOk').hide();
		$('#alertError').hide();
		if(result) {
			$('#alertOk').slideDown();
		} else {
			$('#alertError').slideDown();
		}
	 	setTimeout(function(){
	 		$('#alertIng').slideUp();
	 		$('#alertOk').slideUp();
	 		$('#alertError').slideUp();
	 	}, 2000);
	}

	// 提交前的事件
	function save_before() {

		// 文档ID
		var docID = $('#doc_main_id').val();
		if(docID == '') docID = 0;

		// 标题
		var title = $('#doc_main_title').val();
		if(title == '') {
			title = '无标题文档 - ' + new Date();
			$('#doc_main_title').val(title);
		}

		// 类别
		var cateid = $('#doc_main_cateid').val();

		// 内容
		var content = tinyMCE.get('doc_main_content').getContent();

		// 字数
		var wordcount = getWordCount(content);
		if(wordcount == 0) {
			if(!confirm('内容为空，是否继续保存?'))
				return;
		}

		// 共享
		var shareid = $('#doc_main_shareid').get(0).checked ? 1 : 0

		// 保存文档
		__save(docID, title, cateid, content, wordcount, shareid);
	}

	// 过滤html
	function stripHtml(html) {
	    html = html || "";
	    var scriptregex = "<scr" + "ipt[^>.]*>[sS]*?</sc" + "ript>";
	    var scripts = new RegExp(scriptregex, "gim");
	    html = html.replace(scripts, " ");

	    //Stripts the <style> tags from the html
	    var styleregex = "<style[^>.]*>[sS]*?</style>";
	    var styles = new RegExp(styleregex, "gim");
	    html = html.replace(styles, " ");

	    //Strips the HTML tags from the html
	    var objRegExp = new RegExp("<(.| )+?>", "gim");
	    var strOutput = html.replace(objRegExp, " ");

	    //Replace all < and > with &lt; and &gt;
	    strOutput = strOutput.replace(/</, "&lt;");
	    strOutput = strOutput.replace(/>/, "&gt;");

	    objRegExp = null;
	    return strOutput;
	}

	// 获取字数
	function getWordCount(str) {
		str = stripHtml(str).replace(/ /g, '');
		return str.length;
	}

	// 添加到最近编辑的cookie中
	function addCookie(docid){
		try {
			docid = docid.toString();
			if(docid == '') return;

			var ids = $.cookie('last_edit_docids');
			if(ids == null) {
				ids = docid;
			} else {
				var arr = ids.split('|');
				var news = [ docid ];
				for(i in arr) {
					if(arr[i] != docid) {
						news.push(arr[i]);
					}
				}
				ids = news.slice(0, 6).join('|');
			}
			$.cookie('last_edit_docids', ids);
		} catch(e){}
	}

	$().ready(function(){
		// 修改状态
		var cateid = $('#__cateid').val();
		if(cateid != null && cateid != '') {
			$('#doc_main_cateid option[value='+ $('#__cateid').val() +']').attr('selected', 'true');
		}

		<% if(@isAdd) %>
		new function() {
			var _cateid = '<%=params[:cateid]%>';
			if(_cateid != '') {
				$('#doc_main_cateid option[value='+ _cateid +']').attr('selected', 'true');
			}
		}();
		<% end %>
	});
</script>
